package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.domain.Manager;
import com.example.domain.Result;
import com.example.service.ManagerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/manager")
public class managerController {

    @Autowired
    private ManagerService managerService;

//    分页查询
    @GetMapping
    public Result<Page> page(int size,int pageSize,String name) {
        Page<Manager> managerPage = new Page<>(size, pageSize);
        LambdaQueryWrapper<Manager> managerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        managerLambdaQueryWrapper.like(!StringUtils.isEmpty(name),Manager::getName,name);
        managerLambdaQueryWrapper.orderByAsc(Manager::getName);
        Page<Manager> page = managerService.page(managerPage, managerLambdaQueryWrapper);
        return Result.success(page);
    }

//    添加 add
    @PostMapping
    public Result<String> add (@RequestBody Manager manager) {
        managerService.add(manager);
        return Result.success("添加成功！！！");
    }

//    删除 delete
    @DeleteMapping
    public Result<String> delete (@RequestParam (value = "id")List<Integer> ids) {
        ids.stream().map(id -> {
            managerService.deleteById(id);
            return id;
        }).collect(Collectors.toList());
        if (ids.size() == 1) {
            return Result.success("删除成功！！！");
        } else {
            return Result.success("批量删除成功！！！");
        }
    }

//    通过id来渲染出数据
    @GetMapping("/{id}")
    public Result<Manager> ById(@PathVariable Integer id) {
        Manager byId = managerService.findById(id);
        return Result.success(byId);
    }

//    修改 update
    @PutMapping
    public Result<String> update (@RequestBody Manager manager) {
        managerService.updateManager(manager);
        return Result.success("修改成功！！！");
    }
}
